//
//  CrashLog.m
//  LoseWeight
//
//  Created by shen xiaobai on 12-9-19.
//
//

#import "CrashLog.h"
#import "AppDelegate.h"
#import "UncaughtExceptionHandler.h"
#define LOG @"console.log"
static CrashLog *_crashLog = nil;
@implementation CrashLog

+(void)start
{
    if(_crashLog == nil)
    {
        _crashLog = [[CrashLog alloc]init];
    }
    if([[NSUserDefaults standardUserDefaults] boolForKey:@"CrashLog"])
    {
        NSLog(@"CrashLog yes");
        [_crashLog showAlertView];
    }
    else
    {
        NSLog(@"CrashLog no");
        [_crashLog startLog];
        InstallUncaughtExceptionHandler();
    }
    [_crashLog deviceinfo];
    
    
}

-(void)showAlertView
{
    UIAlertView *alertView = [[UIAlertView alloc]initWithTitle:NSLocalizedString(@"崩溃日志反馈", nil) message:NSLocalizedString(@"是否愿意将崩溃已邮件的形式发送给我们，我们将更好的改进产品。", nil) delegate:self cancelButtonTitle:NSLocalizedString(@"取消", nil) otherButtonTitles:NSLocalizedString(@"确定", nil), nil];
    [alertView show];
    [alertView release];
}

- (BOOL)deleteLogFile {
    
    [self finishLog];
    BOOL success = [[NSFileManager defaultManager] removeItemAtPath:[self loggingPath] error:nil];
    [self startLog];
    return success;
}

- (void)finishLog {
    
    fflush(stderr);
    dup2(dup(STDERR_FILENO), STDERR_FILENO);
    close(dup(STDERR_FILENO));
}

- (NSString*)loggingPath
{
    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSString *documentsDirectory = [paths objectAtIndex:0];
    NSString *logPath = [documentsDirectory stringByAppendingPathComponent:LOG];
    return logPath;
}

- (void)startLog {
    freopen([[self loggingPath] cStringUsingEncoding:NSASCIIStringEncoding],"a+",stderr);
}

- (void)sendLogByMail {
    NSLog(@"sendLogByMail");
     MFMailComposeViewController *picker = [[MFMailComposeViewController alloc] init];
     picker.mailComposeDelegate = self;
    NSArray *toRecipients = [NSArray arrayWithObjects: @"zuzuchen@126.com",@"transsz@126.com",nil];
    [picker setToRecipients: toRecipients];
    [picker setSubject:NSLocalizedString(@"崩溃日志反馈", nil)];
     NSString *message = [NSString stringWithFormat:@"%@%@",NSLocalizedString(@"五子连珠项目", nil),NSLocalizedString(@"开发阶段崩溃日志反馈", nil)];
    [picker setMessageBody:message isHTML:NO];
    NSString *crashlog = [NSString stringWithContentsOfFile:[self loggingPath] encoding:NSUTF8StringEncoding error:nil];
    [picker addAttachmentData:[crashlog dataUsingEncoding:NSUTF8StringEncoding] mimeType:@"log" fileName:LOG];
    
     ;
    
    //AppDelegate * app = (AppDelegate *)[AppDelegate  sharedAppDelegate];
    [[AppController sharedAppDelegate].window.rootViewController presentModalViewController:picker animated:YES];
    
     [picker release];
}

-(void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
{
    if(buttonIndex == 1)
    {
        
        if ([MFMailComposeViewController  canSendMail]) {
            [self sendLogByMail];
            [self deleteLogFile];
        }else{
            [self alertWithMessage:@"崩溃日志无法发送，请添加设置好邮箱"];
        }

    }
    [self startLog];
    InstallUncaughtExceptionHandler();
    [[NSUserDefaults standardUserDefaults]setBool:NO forKey:@"CrashLog"];
    [[NSUserDefaults standardUserDefaults]synchronize];
}

- (void)mailComposeController:(MFMailComposeViewController *)controller
          didFinishWithResult:(MFMailComposeResult)result error:(NSError *)error
{
    NSString *msg = nil;
    switch (result)
    {
        case MFMailComposeResultCancelled:
            msg = nil;
            break;
        case MFMailComposeResultSaved:
            msg = [NSString stringWithFormat:NSLocalizedString(@"邮件已保存", nil)];
            break;
        case MFMailComposeResultSent:
            msg = [NSString stringWithFormat:NSLocalizedString(@"邮件发送成功", nil)];
            break;
        case MFMailComposeResultFailed:
            msg = [NSString stringWithFormat:NSLocalizedString(@"邮件发送失败", nil)];
            break;
        default:
            break;
    }
    [controller dismissModalViewControllerAnimated:YES];
    [self alertWithMessage:msg];
    
}

-(void)alertWithMessage:(NSString *)msg
{
    if (msg == nil) {
        return;
    }
    UIAlertView* alertView = [[UIAlertView alloc] initWithTitle:nil message:msg delegate:nil cancelButtonTitle:NSLocalizedString(@"OK",@"") otherButtonTitles:nil];
    [alertView show];
    [alertView release];
}

-(void)deviceinfo
{
    NSLog(@"name:%@", [[UIDevice currentDevice] name]); // Name of the phone as named by user
    NSLog(@"systemName:%@", [[UIDevice currentDevice] systemName]); // "iPhone OS"
    NSLog(@"systemVersion:%@", [[UIDevice currentDevice] systemVersion]); // "2.2.1"
    NSLog(@"model:%@", [[UIDevice currentDevice] model]); // "iPhone" on both devices
    NSLog(@"localizedModel:%@", [[UIDevice currentDevice] localizedModel]); // "iPhone" on both devices
}
@end
